<template>
  <div>
    <a-button type="primary" shape="round" @click="openModal"
      >创建文件夹</a-button
    >
    &nbsp;
    <!--http://1.12.241.181:8080/file/upload?userPath= -->
<!-- http://localhost:8080/file/upload?userPath=   process.env.VUE_APP_SERVER -->
    <a-upload
      v-model:file-list="fileList"
      name="file"
      :action="
        baseUrl
      +'/file/upload?userPath=' +
        userName +
        '/' +
        rootPath
      "
      :headers="{token: user?.token}"
      @change="handleChange"
      :beforeUpload="beforeUpload"
      :multiple="true"
      style="display: inline-block"
    >
      <a-button type="primary" shape="round">
        <upload-outlined></upload-outlined>
        上传
      </a-button>
    </a-upload>

    <a-table :dataSource="dataSource" :columns="columns" :loading="loading">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'action'">
          <a-button type="primary" style="margin-right: 10px" shape="round">
            <template #icon>
              <DownloadOutlined />
            </template>
          </a-button>
          <a-button
            type="primary"
            danger
            shape="round"
            >
             <a-popconfirm :title="`确认[ ${record.fileName} ]删除吗？`" @confirm="deleteFile(record)">
              <template #icon><question-circle-outlined style="color: red"/></template>
              删除
            </a-popconfirm>
            </a-button>
        </template>
        <template v-if="column.key == 'fileName'">
          <span
            v-if="record.directory"
            @click="goDirectory(record.path)"
            class="file"
          >
            <FolderOpenOutlined />
            {{ record.fileName }}
          </span>
          <span v-else class="file" @click="fileDownload(record)">
            {{ record.fileName }}
          </span>
        </template>
        <template v-if="column.key == 'fileSize'">
          {{ realFileSile(record.fileSize) }}kb
        </template>
      </template>
    </a-table>
    <!-- 模态框用于创建目录 -->
    <a-modal
      v-model:visible="visible"
      title="创建新目录"
      @ok="createDirectory"
      @cancel="cancelCreateDirectory"
    >
      <a-form
        :model="formState"
        name="basic"
        autocomplete="off"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="文件夹名" name="dirName">
          <a-input v-model:value="formState.dirName" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, computed } from "vue";
import {
  UploadOutlined,
  DownloadOutlined,
  FolderOpenOutlined,
} from "@ant-design/icons-vue";
import type { UploadChangeParam, UploadProps } from "ant-design-vue";
import { message } from "ant-design-vue";
import { reqGetFileList, reqDownloadFile, reqDeleteFileOrDir,reqCreateNewDirectory } from "../apis";
import {FileUtils} from '../utils/fileUtil'
import { QuestionCircleOutlined } from "@ant-design/icons-vue";
// import {LocalStoreageUtil} from '../utils/LocalStoreage'
import store from '../store'
declare let process:any;
// 表格列
const columns = [
  {
    title: "文件名",
    dataIndex: "fileName",
    key: "fileName",
  },
  {
    title: "大小",
    dataIndex: "fileSize",
    key: "fileSize",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
  },
];
export default {
  name: "Content",
  components: { UploadOutlined, DownloadOutlined, FolderOpenOutlined,QuestionCircleOutlined },
  setup() {
    let baseUrl =  process.env.VUE_APP_SERVER;
    let loading = ref(false); // 加载效果
    // 当前目录根路径，不包括用户根
    /**
     * 例如：userName: cc
     * rootPath: /qwe
     * 全路径: /cc/qwe
     */
    let rootPath = ref("");
    // let action = ref("http://localhost:8080/file/upload");
    // 用户
    let user = ref();
    // user.value = LocalStoreageUtil.getValue('token');
    let userName = ref("cc");
    // userName.value = user.value.userName;
    // 模态框默认隐藏
    let visible = ref(false);
    // 表单数据,创建目录表达
    let formState = ref();
    formState.value = {};
    // 表格数据
    const dataSource = ref([
      {
        key: "1",
        fileName: "胡彦斌",
        age: 32,
        address: "西湖区湖底公园1号",
      },
    ]);
    // 获取数据
    async function getData(user: any) {
      loading.value = true;
      const res = await reqGetFileList(user);
      if (res.data.success) {
        dataSource.value = res.data.content;
        // console.log(res.data);
        loading.value = false;
      } else {
        throw new Error("加载失败");
      }

    }
    
    // 进入目录
    function goDirectory(path: any) {
      getData({ userName: userName.value, filePath: path });
      // 还需得到目录根
      rootPath.value = path;
      // console.log(path);
    }

    // 文件下载
    async function fileDownload(record: any) {
      // console.log(path);
      let res = await reqDownloadFile({
        userName: userName.value,
        filePath: record.path,
      });
      // 抽取模拟浏览器下载行为作为一个工具类
      FileUtils.fileUpload(res.data, record.fileName);
      //#region 
      // // console.log(res);
      // let fileURL = window.URL.createObjectURL(new Blob([res.data]));
      // //  console.log('fileURL',fileURL)
      // //  创建一个a标签
      // let fileLink = document.createElement("a");

      // fileLink.href = fileURL;
      // //  设置元素属性，为下载的文件添加文件名
      // fileLink.setAttribute("download", record.fileName);
      // //  console.log('fileLink',fileLink);

      // document.body.appendChild(fileLink);
      // fileLink.click();
      // //  释放内存资源
      // window.URL.revokeObjectURL(fileURL);
      //#endregion
    }
    // 删除文件或目录
    async function deleteFile(record: any) {
      // console.log(record);
      let res = await reqDeleteFileOrDir({
        userName: userName.value,
        filePath: record.path,
      });
      console.log("是否删除成功：", res.data);
      if (res.data.success) {
        // 获取最新数据
        // console.log(record.path);
        // 截取字符串,获取最新数据应当是删除后的当前目录
        let currentPath = record.path.slice(0, record.path.lastIndexOf("/"));
        getData({ userName: userName.value, filePath: currentPath });
      }
    }
    // 文件上传列表
    const fileList = ref<UploadProps["fileList"]>([
      //#region 
      // {
      //   uid: "1",
      //   name: "xxx.png",
      //   status: "done",
      //   response: "Server Error 500", // custom error message to show
      //   url: "http://www.baidu.com/xxx.png",
      // },
      //#endregion
    ]);
    // 上传
    const handleChange = ({ file, fileList }: UploadChangeParam) => {
      // 上传成功uploading
      if (file.status == "done") {
        message.success("上传成功!");
        getData({ userName: userName.value, filePath: rootPath.value });
      }
    };
    // 文件上传
    function beforeUpload(file: any) {
      // console.log('fileasdasd',file,'sdsa');
      console.log("rootPath:", rootPath.value);
    }
    // 创建目录
    async function createDirectory() {
      console.log("close");
      // 创建的目录需要拼接上  /根
      console.log(formState.value.dirName);
      if(!formState.value.dirName){
        message.warn("文件夹名不能为空");
        visible.value = false;
        return;
      }
      // 除去两边的空格
      if(!formState.value.dirName.trim()){
        message.warn("文件夹名不能为空");
        visible.value = false;
        return;
      }
      let res = await reqCreateNewDirectory({userName: userName.value,dirName:rootPath.value + '/'+ formState.value.dirName});
      if(res.data.success){
        message.success("创建目录成功");
        getData({ userName: userName.value, filePath: rootPath.value });
      }else {
        message.error(res.data.message);
      }
      visible.value = false;
      // 清空数据
      formState.value = {};

    }
    // 取消创建
    function cancelCreateDirectory() {

      console.log("取消创建");
      // 取消创建了，就需要初始化数据
      formState.value = {};
    }

    function openModal() {
      visible.value = true;
      console.log("打开模态框");
    }
    // 计算属性，计算文件大小
    let realFileSile = computed(() => {
      return function (size: any) {
        return (size / 1024).toFixed(2);
      };
    });
    // 生命周期
    onMounted(() => {
        // console.log('store',store);
      // let u = LocalStoreageUtil.getValue('token');
      // user.value = LocalStoreageUtil.getValue('token');
      user.value = store.state.user;
      userName.value = user.value.userName;
      // console.log("username########:",userName.value);

      getData({ userName: userName.value, filePath: "" });
    
      
    });
    return {
      // 表格和数据
      columns,
      dataSource,
      loading,
      // 打开目录
      goDirectory,
      // 创建目录
      visible,
      createDirectory,
      cancelCreateDirectory,
      openModal,
      formState,

      // 文件下载
      fileDownload,
      // 删除文件（目录）
      deleteFile,

      // 文件大小
      realFileSile,
      beforeUpload,

      // 文件上传
      fileList,
      handleChange,
      rootPath,
      userName,
      user,
// 服务路径url
      baseUrl
    };
  },
};
</script>
<style lang="css">
.file:hover {
  cursor: pointer;
  color: red;
}
</style>